import threading
from PySide6.QtCore import QCoreApplication, Qt, Slot, Signal
from PySide6.QtWidgets import QApplication, QWidget, QTableWidgetItem, QTableWidget, QHBoxLayout, QPushButton

from android_docker import AndroidDocker
from utils import *
from ui.window import Ui_Form
from ui.body import Ui_Body
from android_docker_api import *


class MyWindow(QWidget, Ui_Form):
    instance = None  # 单例模式的实例

    def __new__(cls, *args, **kwargs):
        print("启动")
        if cls.instance is None:
            cls.instance = super(MyWindow, cls).__new__(cls)
        return cls.instance

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 绑定点击按钮
        self.startButton.clicked.connect(self.onClickButton)
        DkGlobal().window = self
        global _G
        # 初始化系统运行
        self.running = False  # 控制线程运行状态的标志变量
        # 初始化容器
        self.dockers = None
        self.setFixedSize(self.width(), self.height())

    # 系统关闭时调用
    def closeEvent(self, event):
        print("关闭")
        self.running = False
        super().closeEvent(event)

    # 点击按钮
    def onClickButton(self):
        if self.running == False:
            self.start()
            # 设置按钮文字为：停用
            self.startButton.setText(QCoreApplication.translate("Form", u"\u505c\u7528", None))
        else:
            # 设置按钮文字为：启用
            self.stop()

    def stop(self):
        self.startButton.setText(QCoreApplication.translate("Form", u"\u542f\u7528", None))
        self.running = False
        win_log("请求系统设备停止运行....")

    # 初始化安卓容器并启用
    def handle_android(self):
        serverIps = self.serverIpTextEdit.toPlainText()
        serverIps = serverIps.split('\n')
        # 超级SDK接口地址
        self.dockers = AndroidDocker(serverIps)
        self.dockers.start_android()

    # 新线程启动安卓容器自动化
    def start(self):
        self.ikuai = {
            "ip": self.ikuai_ip.text(),
            "username": self.ikuai_username.text(),
            "password": self.ikuai_password.text(),
        }
        win_log("启动")
        thread = threading.Thread(target=self.handle_android)
        thread.start()
        self.running = True
        self.hide()
        MyBody().show()


class ButtonCell(QWidget):
    clicked = Signal()

    def __init__(self, text, parent=None):
        super(ButtonCell, self).__init__(parent)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.button = QPushButton(text)
        self.button.clicked.connect(self.clicked.emit)
        layout.addWidget(self.button)
        self.setLayout(layout)


class MyBody(QWidget, Ui_Body):
    instance = None

    def __new__(cls, *args, **kwargs):
        if cls.instance is None:
            cls.instance = super(MyBody, cls).__new__(cls)
        return cls.instance

    def __init__(self):
        if not hasattr(self, '_initialized'):
            super().__init__()
            self._initialized = True
            self.setupUi(self)
            DkGlobal().body = self
            self.bodyRunning = False
            self.task_switch.clicked.connect(self.onTaskClickButton)
            self.tableWidget.cellClicked.connect(self.button_clicked)
            self.setFixedSize(self.width(), self.height())

    def closeEvent(self, event):
        self.bodyRunning = False
        DkGlobal().window.show()
        DkGlobal().window.stop()
        super().closeEvent(event)

    def onTaskClickButton(self):
        if self.bodyRunning == False:
            # 设置按钮文字为：停用
            self.task_switch.setText(QCoreApplication.translate("Form", "停用", None))
            self.bodyRunning = True
        else:
            # 设置按钮文字为：启用
            self.bodyRunning = False
            self.task_switch.setText(QCoreApplication.translate("Form", "启用", None))

    @Slot()
    def on_button_clicked(self, row, column):
        print(f"Button at row {row} and column {column} was clicked.")
        # 根据需要更新状态或其他逻辑

    def populate_table(self, data):
        self.tableWidget.setRowCount(0)
        # 添加新的行
        for row_number, row_data in enumerate(data):
            self.tableWidget.insertRow(row_number)
            for column_number, data in enumerate(row_data):
                item = QTableWidgetItem(str(data))  # 将数据转换成字符串形式
                item.setTextAlignment(Qt.AlignCenter)
                self.tableWidget.setItem(row_number, column_number, item)

    def button_clicked(self, row, column):
        # 在这里定义按钮被点击时的操作
        android_list = DkGlobal().android_docker.android_list
        if column == 8:
            print("row", row)
            key = 0
            for item in android_list:
                if row == key:
                    if android_list[item]['switch'] == False:
                        android_list[item]['switch'] = True
                    else:
                        android_list[item]['switch'] = False
                key += 1
            DkGlobal().android_docker.android_list = android_list
            DkGlobal().android_docker.update_table()


if __name__ == '__main__':
    app = QApplication([])
    window = MyWindow()
    window.show()
    app.exec()
